#!/usr/bin/env python
# -*- coding: utf-8 -*-

from s2c.engine.db_import import import_all
from s2c.engine.downloader import Downloader
from s2c.engine.file_scanner import FileScanner
from s2c.engine.process_scanner import ProcessScanner
from s2c.engine.system_info import SystemInfo
from s2c.rules.conf import SYS_BASE, SYS_CURRENT
from s2c.api.http_server import http_server


class CmdLine:
    def __init__(self, args):
        self.args = args
        self.cmd = None
        self.param = None
        self.param2 = None
        self.parse(args)
        self.execute()

    def parse(self, args):
        if len(args) < 1:
            return
        self.cmd = args[0]
        self.param = None
        self.param2 = None
        # 获取第二个参数
        if len(args) >= 2:
            self.param = args[1]

        if len(args) >= 3:
            self.param2 = args[2]

    def execute(self):
        if len(self.args) < 1:
            usage()
            return
        cmd = self.cmd
        param = self.param

        if cmd == 'init':
            init_scan_all()
        elif cmd == 'info':
            info()
        elif cmd == 'down' or cmd == 'download':
            download()
        elif cmd == 'scan':
            scan_file(param, self.param2)
            scan_process(param)
        # elif cmd == 'scanfile':
        #     scan_file(param,self.param2)
        # elif cmd == 'scanprocess':
        #     scan_process(param)
        elif cmd == 'import':
            import_db()
        elif cmd == 'web':
            # 监听http端口
            if param:
                http_server(param)
            else:
                http_server()
        else:
            usage()  # 帮助手册


def usage():
    msg = '''
    s2c <command> [args],  命令如下:


    web   [port]       显示页面操作界面, port 为端口，默认 9527
    info               获取操作系统信息
    download           下载系统基础文件与进程字典库
    scan                扫描系统文件与进程
    import              将JSON数据导入数据库(可选)
    init                =download + scan +import
    service  <services>  根据服务获取获取关联文件
        - <services>    服务名称
    dockerfile          生成 Dockerfile 文件
    help               显示帮助
'''
    print(msg)


def info():
    SystemInfo().dump()


def download():
    Downloader().down_all()


def scan_file(dict_type, root_path='/'):
    if dict_type != SYS_CURRENT and dict_type != SYS_BASE:
        dict_type = SYS_CURRENT

    if not root_path:
        root_path = ''
    fs = FileScanner(root_path, dict_type=dict_type)
    fs.scan()
    fs.start_task_pool()


def scan_process(param):
    scanner = ProcessScanner(dict_type=param)
    scanner.scan()
    scanner.save()


def init_scan_all():
    fs = FileScanner('/', dict_type=SYS_BASE)
    fs.scan()
    fs.start_task_pool()
    scanner = ProcessScanner(SYS_BASE)
    scanner.scan()
    scanner.save()
    scanner.process_data()


def import_db():
    import_all(SYS_BASE)
    import_all(SYS_CURRENT)

# if __name__ == "__main__":
#     main(sys.argv[1:])
